import java.util.Random;

public class A06_QuicklySortDemo {
    public static void main(String[] args) {
        //定义数组
        //int[] arr = {6, 1, 2, 7, 9, 3, 4, 5, 10, 8};
        int[] arr = new int[1000000];
        Random r = new Random();
        for (int i = 0; i < arr.length; i++) {
            arr[i] = r.nextInt();
        }

        //记录开始时间
        long l1 = System.currentTimeMillis();
        quicklySort(arr, 0, arr.length - 1);
//        for (int i = 0; i < arr.length; i++) {
//            System.out.print(arr[i] + " ");
//        }
        //记录结束时间
        long l2 = System.currentTimeMillis();
        System.out.println(l2 - l1);
    }

    private static void quicklySort(int[] arr, int i, int j) {
        int start = i;
        int end = j;

        //递归结束的条件
        if (start > end) {
            return;
        }
        //定义基准值
        int baseNumber = arr[i];

        while (start != end) {
            //end找到比基准值小的
            while (true) {
                if (end <= start || arr[end] < baseNumber) {
                    break;
                }
                end--;
            }

            //start找到比基准值大的
            while (true) {
                if (end <= start || arr[start] > baseNumber) {
                    break;
                }
                start++;
            }
            //把end和start指向的元素进行交换
            int tmp = arr[start];
            arr[start] = arr[end];
            arr[end] = tmp;
        }

        //当start和end指向同一个内存空间是要进行基准数归位
        int temp = arr[i];
        arr[i] = arr[start];
        arr[start] = temp;

        //确定6左边的范围
        quicklySort(arr, i, start - 1);
        //确定6右边的范围
        quicklySort(arr, start + 1, j);
    }

}
